import { Injectable } from '@nestjs/common';
import { MatchInfoV2 } from './entities/match.entity.v2';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { MatchStatusEnum } from 'src/common/constant/enums';

@Injectable()
export class MatchServiceV2 {
  constructor(
    @InjectRepository(MatchInfoV2)
    private readonly repository: Repository<MatchInfoV2>,
  ) {}

  async getMatchesByTournamentId(tournamentId: number) {
    const matchInfos = await this.repository
      .createQueryBuilder('matchInfo')
      .where('matchInfo.tournamentId = :tournamentId', { tournamentId })
      .leftJoinAndSelect('matchInfo.homePlayer', 'homePlayer')
      .leftJoinAndSelect('matchInfo.awayPlayer', 'awayPlayer')
      .leftJoin('matchInfo.playground', 'playground')
      .addSelect(['playground.name', 'playground.id'])
      .leftJoin('matchInfo.tournament', 'tournament')
      .addSelect('tournament.name')
      .leftJoin('matchInfo.category', 'category')
      .addSelect('category.name')
      .leftJoin('matchInfo.event', 'event')
      .addSelect(['event.name'])
      .leftJoin('matchInfo.stage', 'stage')
      .addSelect(['stage.name', 'stage.stageOrderInEvent'])
      .leftJoin('matchInfo.group', 'group')
      .addSelect('group.name')

      .leftJoinAndSelect('matchInfo.subMatchInfos', 'subMatchInfos')
      .leftJoinAndSelect('subMatchInfos.homePlayer', 'subHomePlayer')
      .leftJoinAndSelect('subMatchInfos.awayPlayer', 'subAwayPlayer')
      .leftJoin('subMatchInfos.playground', 'subMatchPlayground')
      .addSelect(['subMatchPlayground.id', 'subMatchPlayground.name'])

      .getMany();
    matchInfos.forEach((matchItem) => {
      (matchItem as any).stageOrderInEvent = matchItem.stage.stageOrderInEvent;
      [matchItem.homePlayer, matchItem.awayPlayer, matchItem.winner].forEach(
        (v) => {
          if (!v) {
            return;
          }
          if (v.player1Name) {
            v.player = { name: v.player1Name };
          }
          if (v.player2Name) {
            v.player2 = { name: v.player2Name };
          }
          if (v.teamName) {
            (v as any).team = { name: v.teamName };
          }
        },
      );
    });
    return matchInfos;
  }
  async getMatchDetail(matchId: number) {
    const queryBuilder = this.repository
      .createQueryBuilder('matchInfo')
      .where('matchInfo.id = :matchId', { matchId })
      .leftJoinAndSelect('matchInfo.games', 'games')
      .leftJoinAndSelect('matchInfo.playground', 'playground')
      .addSelect('playground.name', 'playground.id')
      .leftJoinAndSelect('matchInfo.rallyRule', 'rallyRule')
      .leftJoinAndSelect('matchInfo.gameRule', 'gameRule')
      // .leftJoinAndSelect('matchInfo.homePlayer', 'homePlayer')
      // .leftJoinAndSelect('matchInfo.awayPlayer', 'awayPlayer')
      .leftJoinAndSelect('matchInfo.subMatchInfos', 'subMatchInfos')
      .leftJoinAndSelect('subMatchInfos.games', 'subGames')
      // .leftJoinAndSelect('subMatchInfos.homePlayer', 'subHomePlayer')
      // .leftJoinAndSelect('subMatchInfos.awayPlayer', 'subAwayPlayer')
      // .leftJoinAndSelect('subMatchInfos.winner', 'subWinner')
      .leftJoinAndSelect('subMatchInfos.rallyRule', 'subRallyRule')
      .leftJoinAndSelect('subMatchInfos.gameRule', 'subGameRule')
      .leftJoinAndSelect('matchInfo.parentMatchInfo', 'parentMatchInfo')
      // .leftJoinAndSelect('parentMatchInfo.homePlayer', 'parentHomePlayer')
      // .leftJoinAndSelect('parentMatchInfo.awayPlayer', 'parentAwayPlayer')
      .leftJoin('matchInfo.tournament', 'tournament')
      .addSelect('tournament.name')
      .leftJoin('matchInfo.category', 'category')
      .addSelect('category.name')
      .leftJoin('matchInfo.event', 'event')
      .addSelect(['event.name'])
      .leftJoin('matchInfo.stage', 'stage')
      .addSelect('stage.name')
      .leftJoin('matchInfo.group', 'group')
      .addSelect('group.name');

    // if (showGameProgress) {
    //   queryBuilder.addSelect('games.progress');
    //   queryBuilder.addSelect('subGames.progress');
    // }

    const matchInfos = await queryBuilder.getOne();

    [matchInfos.homePlayer, matchInfos.awayPlayer, matchInfos.winner].forEach(
      (v) => {
        if (!v) {
          return;
        }
        if (v.player1Name) {
          v.player = { name: v.player1Name };
        }
        if (v.player2Name) {
          v.player2 = { name: v.player2Name };
        }
        if (v.teamName) {
          (v as any).team = { name: v.teamName };
        }
      },
    );
    return matchInfos;
  }
  // async getMatchesByStatusAndTournamentId(
  //   tournamentId: number,
  //   status: MatchStatusEnum,
  // ) {
  //   const matchInfos = await this.repository
  //     .createQueryBuilder('matchInfo')
  //     .leftJoinAndSelect('matchInfo.games', 'games')
  //     .leftJoinAndSelect('matchInfo.group', 'group')
  //     .leftJoinAndSelect('matchInfo.playground', 'playground')
  //     .leftJoinAndSelect('group.stage', 'stage')
  //     .leftJoinAndSelect('stage.event', 'event')
  //     .leftJoinAndSelect('event.category', 'category')
  //     .leftJoinAndSelect('category.tournament', 'tournament')
  //     .where('tournament.id = :tournamentId', { tournamentId })
  //     .andWhere('matchInfo.status = :status', { status })
  //     .getMany();
  //   return matchInfos;
  // }
  async getInProgressMatches(tournamentId: number) {
    // 获取正在进行中的比赛
    const matchInfos = await this.repository
      .createQueryBuilder('matchInfo')
      // .leftJoinAndSelect('matchInfo.homePlayer', 'homePlayer')
      // .leftJoinAndSelect('matchInfo.awayPlayer', 'awayPlayer')
      // .leftJoinAndSelect('matchInfo.winner', 'winner')
      .leftJoin('matchInfo.group', 'group')
      .addSelect(['group.name', 'group.id'])
      // .leftJoinAndSelect('group.stage', 'stage')
      // .leftJoinAndSelect('stage.event', 'event')
      // .leftJoinAndSelect('event.category', 'category')
      // .leftJoinAndSelect('category.tournament', 'tournament')
      .leftJoin('matchInfo.playground', 'playground')
      .addSelect(['playground.name', 'playground.id'])
      .leftJoinAndSelect('matchInfo.games', 'games')
      .leftJoinAndSelect('matchInfo.parentMatchInfo', 'parentMatchInfo')
      // .leftJoinAndSelect('parentMatchInfo.homePlayer', 'parentHomePlayer')
      // .leftJoinAndSelect('parentMatchInfo.awayPlayer', 'parentAwayPlayer')
      // .leftJoinAndSelect('event.eventToPlayers', 'eventToPlayers')
      // .leftJoinAndSelect('eventToPlayers.player', 'player')
      // .leftJoinAndSelect('eventToPlayers.player2', 'player2')
      .where('matchInfo.tournamentId = :tournamentId', { tournamentId })
      .andWhere('matchInfo.status = :status', {
        status: MatchStatusEnum.InProgress,
      })
      .andWhere('matchInfo.playgroundId IS NOT NULL')
      .getMany();

    matchInfos.forEach((matchItem) => {
      [matchItem.homePlayer, matchItem.awayPlayer, matchItem.winner].forEach(
        (v) => {
          if (!v) {
            return;
          }
          if (v.player1Name) {
            v.player = { name: v.player1Name };
          }
          if (v.player2Name) {
            v.player2 = { name: v.player2Name };
          }
          if (v.teamName) {
            (v as any).team = { name: v.teamName };
          }
        },
      );
    });
    return matchInfos;
  }
}
